package com.sq.es.templete;

import cn.hutool.json.JSONUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
/**
 * @Author Li sir
 * @Date 2024/1/8
 * es 和 doc 相关操作
 */
@Component
public class ElasticSearchDocTemplete {

    @Autowired
    private ElasticSearchConnectionTemplete elasticSearchConnectionTemplete;


    public <T> IndexResponse createDoc(T t,String index) {
        RestHighLevelClient connection = elasticSearchConnectionTemplete.getConnection();

        try {
            String jsonStr = JSONUtil.toJsonStr(t);
            IndexRequest indexRequest = new IndexRequest(index);
            indexRequest.source(jsonStr, XContentType.JSON);
            IndexResponse response = connection.index(indexRequest, RequestOptions.DEFAULT);
            return response;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            elasticSearchConnectionTemplete.replaceClient(connection);
        }
    }

    public <T> boolean batchCreateDoc(List<T> list,String index) {
        RestHighLevelClient connection = elasticSearchConnectionTemplete.getConnection();
        try {
            BulkRequest bulk = new BulkRequest();
            for (T t : list) {
                IndexRequest request = new IndexRequest(index);
                String json = JSONUtil.toJsonStr(t);
                System.out.println("json = " + json);
                request.source(json, XContentType.JSON);
                bulk.add(request);
            }
            connection.bulk(bulk,RequestOptions.DEFAULT);
            return true;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            elasticSearchConnectionTemplete.replaceClient(connection);
        }

    }


}
